package cn.phecda.boot.tenant.web.handler;

import cn.phecda.boot.common.lang.model.TenantContext;
import cn.phecda.boot.common.lang.util.HttpHeaderUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * <p> 租户 servlet处理拦截器 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
public class TenantHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantId = HttpHeaderUtils.getTenantId(request);
        TenantContext.set(tenantId);

        String url = request.getRequestURI();
        if (log.isDebugEnabled()) {
            log.debug("|Phecda Boot Tenant|- SET for request [tenantId={}, url={}]", TenantContext.get(), url);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TenantContext.clear();

        String url = request.getRequestURI();
        if (log.isDebugEnabled()) {
            log.debug("|Phecda Boot Tenant|- CLEAR for request [tenantId={}, url={}]", TenantContext.get(), url);
        }
    }
}
